﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SQLite;
using System.Data;

namespace ACLibs.DBHelper.SQLite
{
    public class SQLiteAPI
    {
        public string SQLiteDBFilePathName = ".\\sqlite.db";
        #region 初始化

        /// <summary>
        /// 获取SQLite连接对象
        /// </summary>
        /// <param name="dbfilepathname">SQLite数据库文件</param>
        /// <param name="version">版本号(默认3)</param>
        /// <returns>DBRV对象</returns>
        public DataReturn GetConn(string dbfilepathname,int version = 3)
        {
            using (SQLiteConnection conn = new SQLiteConnection($"Data Source={dbfilepathname};Version={version};"))
            {
                try
                {
                    conn.Open();
                    conn.Close();
                    return new DataReturn() { Success = true, Data = conn };
                }
                catch (Exception x)
                {
                    return new DataReturn() { Success = false, Data = x };
                }
            }
        }

        /// <summary>
        /// 获取SQLite连接对象(使用SQLiteDBFilePathName中数据库)
        /// </summary>
        /// <returns>DBRV对象</returns>
        public DataReturn GetConn()
        {
            return GetConn(SQLiteDBFilePathName, 3);
        }

        #endregion

        #region 数据操作
        public DataReturn ExecNonQuery(string sqlstring)
        {
            try
            {
                DataReturn dbrv = this.GetConn();
                if (!dbrv.Success)
                {
                    return dbrv;
                }
                using (SQLiteConnection conn = dbrv.Data)
                {
                    using (SQLiteCommand comm = new SQLiteCommand(conn))
                    {
                        comm.CommandText = sqlstring;
                        int x = comm.ExecuteNonQuery();
                        return new DataReturn() { Success = true, Data = x };
                    }
                }
            }
            catch(Exception x)
            {
                return new DataReturn() { Success = false, Data = x };
            }
        }

        #endregion
    }
}
